package com.amkai.aes.webservice.binary.objecthandler.inventory;

import com.amkai.aes.aescommon.utilities.EnumHelper;

public class EnumHQLGenerator extends PropertyHQLGenerator {

	private Class<?> enumClass;

	public EnumHQLGenerator(String instanceName, String propertyName, ResolverServiceManager resolverMgr, Class<?> propertyType) {
		super(instanceName, propertyName, resolverMgr);
		this.enumClass = propertyType;
	}

	@Override
	public String getHQLFragment() {
		return String.format("%s.%sWrapper.id = ?", instanceName, propertyName);
	}

	@Override
	public Object getValueFromText(String searchText) {
		Enum<?> enumVal = EnumHelper.findEnumValueFromDescription(enumClass, searchText);
		return (enumVal != null ? enumVal.ordinal() : -1);
	}

	@Override
	public String getHQLPropertyName() {
		if (instanceName == null) {
			return String.format("%sWrapper.id", propertyName);
		} else {
			return String.format("%s.%sWrapper.id", instanceName, propertyName);
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object resolveValue(Object valueToResolve) {
		if (valueToResolve instanceof String) {
			return EnumHelper.findEnumValueFromDescription(enumClass, valueToResolve.toString());
		} else if (valueToResolve instanceof Number) {
			int value = Integer.parseInt(valueToResolve.toString());
			for (Object i : enumClass.getEnumConstants()) {
				if (((Enum)i).ordinal() == value) {
					return i;
				}
			}
		}
		return valueToResolve;
	}

}
